package com.cetcs.kmga.dataManager.controller;

import com.ccsc.auth.entity.ShiroResource;
import com.ccsc.auth.entity.ShiroSystem;
import com.ccsc.auth.entity.ShiroUser;
import com.ccsc.auth.utils.SSOUtil;
import com.cetcs.kmga.common.BaseController;
import com.cetcs.kmga.common.BaseResponse;
import com.cetcs.kmga.common.Constant;
import com.cetcs.kmga.dataManager.annotation.LogAnnotation;
import com.cetcs.kmga.dataManager.entity.global.LogLevelEnum;
import com.cetcs.kmga.dataManager.entity.global.LogTypeEnum;
import com.cetcs.kmga.dataManager.entity.sysMenu.SysMenu;
import com.cetcs.kmga.dataManager.util.CommonUtils;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/11/16 0016.
 */
@RestController
@RequestMapping(value = "/auth")
public class MenuController extends BaseController {

//    @Autowired
//    private UserService userService;

    public static final String SSO_SECRET_KEY = "superAdmin";
    public static final String SSO_APP_KEY = "data";

    private static final String SYS_IDENTIFIER = "data";
    private static final String CURRENT_SYS_IDENTIFIER_NAME = "数据监管系统";

    /**
     * 获取系统目录
     */
    @LogAnnotation(module = "菜单管理", logType = LogTypeEnum.业务日志, description = "获取系统目录", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/getSys", method = RequestMethod.GET, produces = {"application/json", "application/xml"})
    public BaseResponse getSys() throws Exception {
        List<Map<String, Object>> list = Lists.newLinkedList();
        try {
            ShiroUser sessionUser = getSessionUser();
            if (sessionUser == null) {
                return this.error(Constant.SYSTEM_EXCEPTION, "未登录不能获取菜单");
            }

            //userService.getUserInfo(String.valueOf(sessionUser.getUserId()));

            List<ShiroSystem> systemList = sessionUser.getSystems();
            for (ShiroSystem shiroSystem : systemList) {
                if (!SSO_APP_KEY.equals(shiroSystem.getSystemIdentifier())) {
                    ImmutableMap<String, Object> map = ImmutableMap.of("systemId", shiroSystem.getSystemId(), "systemName", shiroSystem.getSystemName(),"systemIdentifier",shiroSystem.getSystemIdentifier(), "systemUrl", shiroSystem.getSystemUrl());
                    list.add(map);
                }
            }
            list.sort((Map<String, Object> v1, Map<String, Object> v2) -> CommonUtils.convertStr(v2.get("systemId")).compareTo(CommonUtils.convertStr(v1.get("systemId"))));
            return this.ok(list);
        } catch (Exception e) {
            e.printStackTrace();
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }

    /**
     * 获取菜单
     */
    @LogAnnotation(module = "菜单管理", logType = LogTypeEnum.业务日志, description = "获取菜单", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/getMenu", method = RequestMethod.GET)
    public BaseResponse findSysMenu() {
        try {
            ShiroUser sessionUser = getSessionUser();
            if (sessionUser == null) {
                return this.error(Constant.SYSTEM_EXCEPTION, "未登录不能获取菜单");
            }
            List<ShiroResource> shiroResources = Lists.newArrayList();
            List<SysMenu> menuVoList = Lists.newArrayList();
            if (sessionUser != null) {
                shiroResources = SSOUtil.getResourcesBySysKey(sessionUser, SYS_IDENTIFIER);

                if (shiroResources != null && shiroResources.size() > 0) {
                    for (ShiroResource shiroResource : shiroResources) {
//                        if (shiroResource.getResourceParentId() == null || shiroResource.getResourceParentId() == 0) {
//                            SysMenu root = convResource2MenuVo(shiroResource);
//                            menuVoList.add(getMenuChilds(root, shiroResources));
//                        }
                        menuVoList.add(convResource2MenuVo(shiroResource));
                    }
                }

                if(menuVoList.size()>0) {
                    return this.ok(resourceList2ChildList(menuVoList, null));
                }else{
                    return this.error(Constant.SYSTEM_EXCEPTION, "无访问权限");
                }

            } else {
                return this.error(Constant.NOT_FOUND, "未获得菜单");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }

    //获取用户信息
    @LogAnnotation(module = "菜单管理", logType = LogTypeEnum.业务日志, description = "获取用户信息", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/getUser", method = RequestMethod.GET)
    public BaseResponse getUserInfo() throws Exception {
        try{
            ShiroUser sessionUser = getSessionUser();
            return this.ok(sessionUser.getUserName());
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return this.ok("未知用户");
        }
    }

    /**
     *将平行的资源树转化层级资源树
     * @param resourceList
     * @param parentNum
     * @return
     */
    public static List<SysMenu> resourceList2ChildList(List<SysMenu> resourceList, Integer parentNum){
        List<SysMenu> temp=new LinkedList<SysMenu>();
        if(resourceList.size()==0){return null;}
        for (int i=0; i<resourceList.size(); i++) {
            if(resourceList.size()==0){break ;}
            SysMenu menuVo = resourceList.get(i);
            if(parentNum!=null) {
                if(menuVo.getpId()==null || menuVo.getpId() == 0){continue;}
                if (parentNum==menuVo.getpId()) {
                    resourceList.remove(i);
                    i--;
                    menuVo.setChilds(resourceList2ChildList(resourceList, menuVo.getId()));
                    if (menuVo.getChilds() == null){
                        menuVo.setChilds(new LinkedList<SysMenu>());
                    }
                    temp.add(menuVo);
                }
            }else {
                if (menuVo.getpId()==null || menuVo.getpId() == 0) {
                    resourceList.remove(i);
                    i--;
                    menuVo.setChilds(resourceList2ChildList(resourceList, menuVo.getId()));
                    temp.add(menuVo);
                }
            }
        }
        return temp;
    }

    private SysMenu getMenuChilds(SysMenu root, List<ShiroResource> shiroResources) {
        List<SysMenu> children = new ArrayList<>();
        shiroResources.forEach(p -> {
            if (root.getId() == p.getResourceParentId()) {
                SysMenu childVo = convResource2MenuVo(p);
                children.add(childVo);
            }
        });
        root.setChilds(children);
        return root;
    }

    private SysMenu convResource2MenuVo(ShiroResource resource) {
        SysMenu menuVo = new SysMenu();
        menuVo.setId(resource.getResourceId());
        menuVo.setName(resource.getResourceDescription());
        menuVo.setUrl(resource.getResourceContent());
        menuVo.setpId(resource.getResourceParentId());
        menuVo.setIcon(resource.getResourceIcon());
        menuVo.setModuleType(resource.getResourceType());
        return menuVo;
    }

}
